﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using UnityEngine;

namespace Dict
{
    public class DictFileReader
    {
        private TextReader reader;
        private MemoryStream memoryStream = null;
        private char[] splitChars = { '\t' };
        public DictFileReader(string filePath)
        {
#if UNITY_EDITOR && !TESTASSET
            reader = new StreamReader("Assets/OutputBundle/" + filePath);
#else
            if (Application.isPlaying)
            {
                string fileName = filePath.Substring(0, filePath.Length - 4);
                AssetBundle ab = AssetLoad.AssetBundleManager.Instance.GetBundleSimple(fileName);
                fileName = fileName.Substring(fileName.LastIndexOf("/") + 1);
                TextAsset ta = ab.LoadAsset(fileName) as TextAsset;
                memoryStream = new MemoryStream(ta.bytes);
                reader = new StreamReader(memoryStream);
                ab.Unload(false);
            }
            else
            {
                reader = new StreamReader("Assets/OutputBundle/" + filePath);
            }
#endif
        }

        public string[] ReadRow()
        {
            string line = reader.ReadLine();
            if (line == null)
            {
                return null;
            }
            return line.Split(splitChars,System.StringSplitOptions.None);
        }

        public string[] ReadLine(int i)
        {
            List<string> lines = new List<string>();
            string line = null;
            do
            {
                line = reader.ReadLine();
                if (line != null)
                {
                    string[] rowLines = line.Split(splitChars,System.StringSplitOptions.None);
                    lines.Add(rowLines[i]);
                }
            } while (line != null);
            return lines.ToArray();
        }

        public void Dispose()
        {
            reader.Close();
            reader.Dispose();
            reader = null;
            if (memoryStream != null)
            {
                memoryStream.Close();
                memoryStream.Dispose();
            }
            memoryStream = null;
        }
    }
}
